package stravel

import grails.plugin.springsecurity.*
import org.springframework.security.access.annotation.Secured

@Secured('permitAll')
class HomeController {

	def index() {
		def hotelList = []
		def totalRecord = 0
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		params.offset = params.offset ? params.int('offset') :0
		if(params.name){
			def c = Hotel.createCriteria()
			hotelList = c.list{
				or{
					ilike("name", "%${params.name}%")
					city{
						ilike("name", "%${params.name}%")
					}
				}
				order('rate',"desc")
				maxResults(params.max)
				firstResult(params.offset)
			}

			def c2 = Hotel.createCriteria()
			totalRecord = c2.count{
				or{
					ilike("name", "%${params.name}%")
					city{
						ilike("name", "%${params.name}%")
					}
				}
			}
		}
		[hotelList:hotelList, totalRecord:totalRecord]
	}

	def logout(){
		redirect(action:'index')
	}

	def advanced(){
		def hotelList = []
		def totalRecord = 0
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		params.offset = params.offset ? params.int('offset') :0
		if(params.name || params.stateId || params.cityId || params.starId){
			def c = Hotel.createCriteria()
			hotelList = c.list{
				if(params.name){
					like("name", "%${params.name}%")
				}
				if(params.starId){
					eq("starRating.id", new Long(params.starId))
				}
				if(params.stateId){
					eq("state.id", new Long(params.stateId))
				}
				if(params.cityId){
					eq("city.id", new Long(params.cityId))
				}

				maxResults(params.max)
				firstResult(params.offset)
			}

			def c2 = Hotel.createCriteria()
			totalRecord = c2.count{
				if(params.name){
					like("name", "%${params.name}%")
				}
				if(params.starId){
					eq("starRating.id", new Long(params.starId))
				}
				if(params.stateId){
					eq("state.id", new Long(params.stateId))
				}
				if(params.cityId){
					eq("city.id", new Long(params.cityId))
				}
			}
		}
		[hotelList:hotelList, totalRecord:totalRecord]
	}
}
